<template>
  <view class="filter-wrap">
    <!-- <view class="rank-name">
      <image class="icon" src="@/static/icons/rank.png" />
      镇(街)活动预约榜
    </view> -->
    <view>
      <DatePicker v-model:date="date" @confirm="confirm" />
    </view>
  </view>
  <view class="chart-wrap">
    <BarChart :axis-data="axisData" :data="barData" :height="barHeight" ref="chartRef" />
  </view>
</template>

<script setup>
import DatePicker from './DatePicker.vue'
import BarChart from './BarChart.vue'
import BiApi from '@/service/bi'
import dayjs from 'dayjs'

const date = ref([])

const formatDate = ref([])

const initDate = () => {
  const today = new Date().getTime()
  const thirtyDaysAgo = new Date().getTime() - 30 * 24 * 60 * 60 * 1000
  date.value = [new Date(thirtyDaysAgo), new Date(today)]

  formatDate.value = [
    dayjs(date.value[0]).format('YYYY-MM-DD'),
    dayjs(date.value[1]).format('YYYY-MM-DD'),
  ]
}

const confirm = () => {
  formatDate.value = [
    dayjs(date.value[0]).format('YYYY-MM-DD'),
    dayjs(date.value[1]).format('YYYY-MM-DD'),
  ]
  getData()
}

const axisData = ref([])
const barData = ref([])
const barHeight = ref(300)

const chartRef = ref()

const getData = async () => {
  barData.value = []
  axisData.value = []
  const ret = await BiApi.getTownReport({
    startDate: formatDate.value?.[0] || '',
    endDate: formatDate.value?.[1] || '',
  })

  if (ret?.result?.length > 0) {
    ret.result.forEach((item) => {
      barData.value.unshift(item.value)
      axisData.value.unshift(item.label)
    })
    barHeight.value = 30 * ret.result.length
  } else {
    barHeight.value = 300
  }
  chartRef.value.initData()
}

const initData = () => {
  initDate()
  getData()
}

defineExpose({
  initData,
  getData,
})
</script>

<style lang="scss" scoped>
.rank-name {
  display: flex;
  align-items: center;

  image {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
}
</style>
